package com.longtop.perform.zb.system.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import com.longtop.framework.base.BaseService;
import com.longtop.framework.common.Constant;
import com.longtop.framework.common.QueryConditions;
import com.longtop.framework.common.QueryResult;
import com.longtop.framework.security.BaseCheckedException;
import com.longtop.framework.security.SessionObject;
import com.longtop.framework.util.StringUtil;
import com.longtop.perform.zb.system.model.TZbSystem;
import com.longtop.perform.zb.system.model.TZbSystemClass;
import com.longtop.perform.zb.system.model.TZbSystemClassMx;

public class SystemService extends BaseService {

	public static final String BEAN_ID = "systemService";

	/**
	 * 保存、修改、删除一起做！
	 * 
	 * @param changeMap
	 *            对象列表，有三个值，删除主键列表、更新bean的列表、新增bean的列表
	 * @param sessionObject
	 * @return 操作成功受影响的记录数，有三个值，插入成功的记录数、更新成功的记录数、删除成功的记录数
	 */
	public Integer[] saveSystem(Map changeMap, SessionObject sessionObject) throws BaseCheckedException {

		// 插入成功的记录数、更新成功的记录数、删除成功的记录数
		int insertCount = 0;
		int updateCount = 0;
		int deleteCount = 0;

		// 删除主键列表、更新bean的列表、新增bean的列表
		List insertBeanList = (ArrayList) changeMap.get(Constant.INSERT_BEAN_LIST);
		List updateBeanList = (ArrayList) changeMap.get(Constant.UPDATE_BEAN_LIST);
		String idList = (String) changeMap.get(Constant.ID_LIST);

		TZbSystem zbSystem;
		Iterator iterator;

		// 批量插入记录
		if (insertBeanList.size() > 0) {
			iterator = insertBeanList.iterator();
			while (iterator.hasNext()) {
				zbSystem = (TZbSystem) iterator.next();
				this.setAuthPropetryToEntity(zbSystem, sessionObject, true);
				// 校验id是否重复。
				if (isExistSystemId(zbSystem.getSystemId()))
					throw new BaseCheckedException("", "保存失败,指标体系ID【" + zbSystem.getSystemId() + "】已经存在!");

				super.save(zbSystem);
				insertCount++;
			}
		}

		// 批量更新记录
		if (updateBeanList.size() > 0) {
			iterator = updateBeanList.iterator();
			while (iterator.hasNext()) {
				zbSystem = (TZbSystem) iterator.next();
				this.setAuthPropetryToEntity(zbSystem, sessionObject, false);
				super.update(zbSystem);
				updateCount++;
			}
		}

		// 批量删除记录
		if (idList.length() > 0) {
			String[] systemIds = idList.split(",");
			// 验证

			//
			for (int i = 0; i < systemIds.length; i++) {
				String systemId = systemIds[i];
				// 删除指标下分类及其关联
				deleteSystemClassBySystemId(systemId);
				String sql = "delete from TZbSystem where systemId in(" + systemId + ")";
				super.batchUpdate(sql);
				deleteCount++;
			}
		}

		return new Integer[] { new Integer(insertCount), new Integer(updateCount), new Integer(deleteCount) };
	}

	/**
	 * 验证此 指标配置 Id 是否存在
	 * 
	 * @param menuId
	 * @return
	 */
	private boolean isExistSystemId(String systemId) {
		boolean flag = false;

		List list = this.queryAll("from TZbSystem where systemId='" + systemId + "'");

		if (list.size() > 0)
			flag = true;

		return flag;
	}

	/**
	 * 依据条件，读取指标配置列表
	 * 
	 * @param queryConditions
	 *            查询条件
	 * @param pageNo
	 *            查询结果的起始页码。
	 * @param pageSize
	 *            查询结果的最大行数。如果不需要，则设置为-1
	 * @return
	 */
	public QueryResult loadSystem(QueryConditions queryConditions, int pageNo, int pageSize) {

		String hql = "from TZbSystem";
		String orderBy = "systemId asc";
		String[] propertyNames = null;
		String[] operators = null;
		Object[] values = null;

		if (queryConditions != null) {
			propertyNames = StringUtil.listToStrArray(queryConditions.getPropertyNames());
			operators = StringUtil.listToStrArray(queryConditions.getOperators());
			List valuesList = queryConditions.getValues();

			if (valuesList != null || valuesList.size() > 0)
				values = valuesList.toArray();
		}

		int offset = (pageNo - 1) * pageSize;

		// 执行查询
		Object[] result = this.query(hql, propertyNames, operators, values, offset, pageSize, true, orderBy, null, null);

		return new QueryResult((List) result[0], result[1] != null ? ((Integer) result[1]).intValue() : 0);
	}

	/**
	 * 复制指标体系
	 * 
	 * @param systemId
	 * @throws BaseCheckedException
	 */
	public void saveZbSystem(String systemId, SessionObject sessionObject) throws BaseCheckedException {

		// 复制指标体系
		List zbSystems = this.queryAll("from TZbSystem where systemId='" + systemId + "'");
		TZbSystem zbSystem = (TZbSystem) zbSystems.get(0);
		TZbSystem zbSystemCopy = new TZbSystem();
		String copyName = "_副本";
		String copyId = "_copy";
		String systemCopyId = systemId + copyId;
		int copyTime = 0;
		while (isExistSystemId(systemCopyId)) {
			copyTime++;
			copyId = "_copy" + "(" + copyTime + ")";
			copyName = "_副本" + "(" + copyTime + ")";
			systemCopyId = systemId + copyId;
		}
		zbSystemCopy.setRemark(zbSystem.getRemark());
		zbSystemCopy.setSystemDesc(zbSystem.getSystemDesc());
		zbSystemCopy.setSystemName(zbSystem.getSystemName() + copyName);
		zbSystemCopy.setFitObject(zbSystem.getFitObject());
		zbSystemCopy.setSystemId(systemCopyId);

		this.setAuthPropetryToEntity(zbSystemCopy, sessionObject, true);

		super.save(zbSystemCopy);

		// 复制指标体系中的类
		List zbSystemClasses = this.queryAll("from TZbSystemClass where systemId='" + systemId + "'");
		for (int i = 0; i < zbSystemClasses.size(); i++) {
			TZbSystemClass zbSystemClass = (TZbSystemClass) zbSystemClasses.get(i);
			String zbSystemClassId = zbSystemClass.getClassId();
			TZbSystemClass zbSystemClassCopy = new TZbSystemClass();
			zbSystemClassCopy.setClassDesc(zbSystemClass.getClassDesc());
			zbSystemClassCopy.setClassId(zbSystemClassId + copyId);
			zbSystemClassCopy.setClassName(zbSystemClass.getClassName() + copyName);
			zbSystemClassCopy.setRemark(zbSystemClass.getRemark());
			zbSystemClassCopy.setSystemId(zbSystemCopy.getSystemId());
			zbSystemClassCopy.setParentClassId(zbSystemClass.getParentClassId() + copyId);
			super.save(zbSystemClassCopy);
			saveTZbSystemClassMx(zbSystemClassId, zbSystemClassId + copyId);
		}

	}

	public void saveTZbSystemClassMx(String classId, String copyClassId) throws BaseCheckedException {
		List zbSystemClassIndexes = this.queryAll("from TZbSystemClassMx where classId='" + classId + "'");
		for (int i = 0; i < zbSystemClassIndexes.size(); i++) {
			TZbSystemClassMx zbSystemClassIndex = (TZbSystemClassMx) zbSystemClassIndexes.get(i);
			TZbSystemClassMx zbSystemClassIndexCopy = new TZbSystemClassMx();
			zbSystemClassIndexCopy.setClassId(copyClassId);
			zbSystemClassIndexCopy.setIndexId(zbSystemClassIndex.getIndexId());
			super.save(zbSystemClassIndexCopy);
		}
	}

	/**
	 * 删除指标体系下的指标分类和其关联指标
	 * 
	 * @param systemId
	 * @throws BaseCheckedException
	 */
	public void deleteSystemClassBySystemId(String systemId) throws BaseCheckedException {
		String selectClasssql = "from TZbSystemClass where systemId=" + systemId;
		List zbSystemClasses = this.queryAll(selectClasssql);

		// 删除指标分类关联指标
		String classIds = "";
		for (int i = 0; i < zbSystemClasses.size(); i++) {
			TZbSystemClass zbSystemClass = (TZbSystemClass) zbSystemClasses.get(i);
			String classId = zbSystemClass.getClassId();
			if (i > 0) {
				classIds = classIds + ",'" + classId + "'";
			} else {
				classIds = classIds + "'" + classId + "'";
			}
		}
		if (!"".equals(classIds)) {
			String sql = "delete from TZbSystemClassMx where classId in (" + classIds + ")";
			super.batchUpdate(sql);
		}
		// 删除指标分类
		this.deleteAll(zbSystemClasses);
	}
}